const path = require('path')
const {
  publicPath,
  outputDir,
  assetsDir,
  indexPath,
  title,
  productionSourceMap,
  filenameHashing,
  lintOnSave,
  webpackBarName,
  webpackBanner,
  devPort,
  devOpen,
  providePlugin,
} = require('./src/config')
const { version, author } = require('./package.json')
const Webpack = require('webpack')
const WebpackBar = require('webpackbar')
const dayjs = require('dayjs')
const time = dayjs().format('YYYY-M-D HH:mm:ss')
process.env.VUE_APP_TITLE = title || 'vue-antd-demo'
process.env.VUE_APP_AUTHOR = author || 'jiangkunyun'
process.env.VUE_APP_UPDATE_TIME = time
process.env.VUE_APP_VERSION = version

const resolve = (dir) => {
  return path.join(__dirname, dir)
}

const mockServer = () => {
  //开发环境使用模拟数据
  if (process.env.NODE_ENV === 'development') {
    return require('./mock/mockServer.js')
  } else {
    return ''
  }
}

// 具体配置https://cli.vuejs.org/zh/config/
module.exports = {
  publicPath,
  outputDir,
  assetsDir,
  indexPath,
  filenameHashing,
  lintOnSave,
  // 提供虚拟服务器，进行开发和调试
  devServer: {
    //热加载
    hot: true,
    // 主机名
    host: 'localhost',
    // 端口
    port: devPort,
    //启动后自动打开浏览器
    open: devOpen,
    //启用 noInfo 后，诸如「启动时和每次保存之后，
    //那些显示的 webpack 包(bundle)信息」的消息将被隐藏。错误和警告仍然会显示。
    noInfo: false,
    //当出现编译器错误或警告时，显示浏览器中的全屏覆盖。默认禁用。
    overlay: {
      warnings: true,
      errors: true,
    },
    // 注释掉的地方是前端配置代理访问后端的示例
    // proxy: {
    //   [baseURL]: {
    //     target: `http://你的后端接口地址`,
    //     ws: true,
    //     changeOrigin: true,
    //     pathRewrite: {
    //       ["^/" + baseURL]: "",
    //     },
    //   },
    // },
    before: mockServer(),
  },
  configureWebpack() {
    return {
      resolve: {
        alias: {
          '@': resolve('src'),
          '*': resolve(''),
        },
      },
      plugins: [
        new Webpack.ProvidePlugin(providePlugin),
        new WebpackBar({
          name: webpackBarName, //启动打包进度条文案
        }),
      ],
    }
  },
  chainWebpack(config) {
    config.resolve.symlinks(true)
    config.module.rule('svg').exclude.add(resolve('src/icon/remixIcon')).end()

    config.module
      .rule('remixIcon')
      .test(/\.svg$/)
      .include.add(resolve('src/icon/remixIcon'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({ symbolId: 'remix-icon-[name]' })
      .end()

    config.when(process.env.NODE_ENV === 'development', (config) => {
      config.devtool('source-map')
    })

    config.when(process.env.NODE_ENV !== 'development', (config) => {
      config.performance.set('hints', false)
      config.devtool('none')
      //vue-cli3 打包优化之 splitchunks https://blog.csdn.net/DongFuPanda/article/details/104888028
      config.optimization.splitChunks({
        chunks: 'all', //async异步代码分割 initial同步代码分割 all同步异步分割都开启
        cacheGroups: {
          //缓存组，将所有加载模块放在缓存里面一起分割打包
          libs: {
            //自定义打包模块
            name: webpackBarName + '-lib', // 打包后的文件名
            test: /[\\/]node_modules[\\/]/, //将node_modules下的模块打包在一起
            priority: 10, //优先级，先打包到哪个组里面，值越大，优先级越高
            chunks: 'initial', //代码块类型 必须三选一： “initial”（初始化） | “all”(默认就是 all) | “async”（动态加载）
          },
        },
      })
      //代码添加版权信息
      config
        .plugin('banner')
        .use(Webpack.BannerPlugin, [`${webpackBanner}${time}`])
        .end()
      //图片压缩
      config.module
        .rule('images')
        .use('image-webpack-loader')
        .loader('image-webpack-loader')
        .options({
          bypassOnDebug: true,
        })
        .end()
    })
  },
  runtimeCompiler: true,
  productionSourceMap,
  css: {
    requireModuleExtension: true,
    sourceMap: true,
  },
}
